import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Form, Row, Col, Input, Button, Table, message, Select } from 'antd'
import { UpOutlined, DownOutlined } from '@ant-design/icons'
// import moment from 'moment'
import { addWindow } from '@redux/actions'
import style from '../filingCaseManage/CaseManage.module.less'
import CaseNoRender from '@components/CaseNoRender'
import { strToNum } from '@src/assets/js/tool'

const { Item } = Form
const { Option } = Select

const layout = {
  labelCol: { flex: '72px' }
}

// 获取表格字段配置
function getColumns () {
  const list = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '案号',
      dataIndex: 'caseno_desc',
      key: 'caseno_desc',
      width: 130,
      sorter: true,
      render: (v, l) => {
        return <CaseNoRender data={l} />
      }
    },
    {
      title: '申请人',
      dataIndex: 'applicant_name',
      key: 'applicant_name',
      width: 150
    },
    {
      title: '被申请人',
      dataIndex: 'respondent_name',
      key: 'respondent_name',
      width: 150
    },
    {
      title: '案由',
      dataIndex: 'cause_action',
      key: 'cause_action',
      width: 150
    },
    {
      title: '办案秘书',
      dataIndex: 'processer',
      key: 'processer',
      width: 100
    },
    {
      title: '组庭届满',
      dataIndex: 'arbitrator_sel_limit',
      key: 'arbitrator_sel_limit',
      sorter: true,
      width: 140
    },
    {
      title: '审限',
      dataIndex: 'trial_limit',
      key: 'trial_limit',
      width: 120,
      sorter: true,
      align: 'right',
      render: v => {
        if (!v) {
          return undefined
        }
        v = strToNum(v)
        if (v > 0) {
          return `${v}天`
        } else {
          return <span style={{ color: 'red' }}>{v}天</span>
        }
      }
    },
    {
      title: '呈批中',
      dataIndex: 'inflow',
      key: 'inflow',
      width: 120,
      align: 'center',
      render: (v) => {
        return v === 1 ? '是' : '否'
      }
    },
    {
      title: '操作',
      dataIndex: 'index',
      key: 'operate',
      width: 120,
      render: (value, line) => {
        return (<span className={style['operate-btn']} onClick={() => this.openDetail(line)}>详情</span>)
      }
    }
  ]
  return list
}

class AllWarningCase extends Component {
  state = {
    searchToggleBtn: false,
    loading: false,
    list: [],
    orderField: '',
    order: '',
    typeList: ['延期审限', '已延期审限', '即将延期组庭', '已延期组庭'],
    activeType: '延期审限',
    type: 'trial_limit',
    degree: 'warning',
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    },
    secretaryList: []
  }

  formRef = React.createRef()

  // 查看案件详情
  openDetail (data) {
    this.props.addWindow({ id: `CaseDetail-${data.id}`, title: `案件详情-${data.caseno_desc || data.acceptno_desc || data.case_no || data.accept_no || data.serial_no}`, componentName: 'CaseDetail', forceRefresh: true, meta: { id: data.id } })
  }

  // 改变案件状态
  changeStatus (status) {
    this.setState({
      status,
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  // 获取秘书列表
  getSecretaryList () {
    this.$get('/api/xapc/employee/getCaseProcesser')
      .then(res => {
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        this.setState({
          secretaryList: res.data
        })
      })
  }

  // 获取案件数据
  getTableData (form) {
    form = form || this.formRef.current.getFieldsValue()
    const { pagination, orderField, order, type, degree } = this.state
    const { current, pageSize } = pagination
    const condition = []
    if (form.caseno) {
      condition.push({ k: 'caseno_desc|counter_caseno_desc', o: 'like', v: `%${form.caseno}%` })
    }
    if (form.applicant) {
      condition.push({ k: 'applicant_name', o: 'like', v: `%${form.applicant}%` })
    }
    if (form.respondent) {
      condition.push({ k: 'respondent_name', o: 'like', v: `%${form.respondent}%` })
    }
    if (form.processerid) {
      condition.push({ k: 'processerid', o: '=', v: form.processerid })
    }
    if (form.arbitrator) {
      condition.push({ k: 'arbitrators', o: 'like', v: `%${form.arbitrator}%` })
    }
    const data = {
      current,
      page_size: pageSize,
      condition: JSON.stringify(condition),
      type,
      degree,
      statusex: form.statusex
    }
    if (orderField && order) {
      data.order = order === 'ascend' ? 'asc' : 'desc'
      data.order_field = orderField
    }
    this.setState({ loading: true })
    this.$get('/api/xapc/casestat/limitStat', data).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        this.setState({
          list: res.data.list.map((li, i) => {
            li.key = pageSize * (current - 1) + i + 1
            return li
          }),
          pagination: {
            ...pagination,
            total: res.data.total
          }
        })
      } else {
        return message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  // 表格请求变化
  tableChange ({ current, pageSize }, filters, sorter) {
    this.setState({
      orderField: sorter.field,
      order: sorter.order,
      pagination: {
        ...this.state.pagination,
        current,
        pageSize
      }
    }, () => {
      this.getTableData()
    })
  }

  // 重置表格
  resetHandle () {
    this.formRef.current.resetFields()
    this.setState({
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  // 根据传参格式化表单
  initFormByMeta () {
    const c = this.formRef.current
    const { activeType } = this.props.meta || {}
    c.resetFields()
    if (activeType) {
      this.toggleType(activeType)
    } else {
      c.submit()
    }
  }

  // 切换类型
  toggleType (t) {
    let type = ''
    let degree = ''
    switch (t) {
      case '延期审限':
        type = 'trial_limit'
        degree = 'warning'
        break
      case '已延期审限':
        type = 'trial_limit'
        degree = 'over'
        break
      case '即将延期组庭':
        type = 'arbitrator_sel_limit'
        degree = 'warning'
        break
      case '已延期组庭':
        type = 'arbitrator_sel_limit'
        degree = 'over'
        break
      default:
        break
    }
    this.setState({
      activeType: t,
      type,
      degree
    }, () => {
      this.getTableData()
    })
  }

  componentDidUpdate (prev) {
    if (prev.meta !== this.props.meta) {
      this.initFormByMeta()
    }
  }

  componentDidMount () {
    this.getSecretaryList()
    this.initFormByMeta()
  }

  // 渲染搜索表单的展开和收起
  renderToggleBtns () {
    if (this.state.searchToggleBtn) {
      return (
        <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
          <span>展开</span>
          <UpOutlined />
        </Button>
      )
    }
    return (
      <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
        <span>收起</span>
        <DownOutlined />
      </Button>
    )
  }

  // 渲染类型切换
  renderTypeToggle () {
    return this.state.typeList.map((li, i) => {
      const c = [style['type-btn']]
      if (li === this.state.activeType) {
        c.push(style.active)
      }
      return (
        <div key={i} className={c.join(' ')} onClick={() => this.toggleType(li)}>
          <span className={style['type-btn-text']}>{li}</span>
        </div>
      )
    })
  }

  render () {
    const initialValues = { statusex: '在办' }
    const columns = getColumns.call(this)
    return (
      <div className={style.container}>
        <div className={style['title-line']}>
          <span>{this.props.title}</span>
        </div>
        <div className={style['type-container']}>
          {this.renderTypeToggle()}
        </div>
        <div className={style['search-container']}>
          <div className={style['search-form']}>
            <Form name='my_case_manage' {...layout} ref={this.formRef} initialValues={initialValues} onFinish={v => this.getTableData(v)}>
              <Row gutter={24}>
                <Col span={8}>
                  <Item label='案号' name='caseno'>
                    <Input placeholder='请输入案号' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='申请人' name='applicant'>
                    <Input placeholder='请输入申请人' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='被申请人' name='respondent'>
                    <Input placeholder='请输入被申请人' />
                  </Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col span={8}>
                  <Item label='案件状态' name='statusex'>
                    <Select placeholder='请选择案件状态'>
                      <Option key='全部'>全部</Option>
                      <Option key='在办'>在办</Option>
                      <Option key='已结案'>已结案</Option>
                    </Select>
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='办案秘书' name='processerid'>
                    <Select placeholder='请选择办案秘书'>
                      {this.state.secretaryList.map(li => <Option key={li.id} value={li.id}>{li.name}</Option>)}
                    </Select>
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='仲裁员' name='arbitrator'>
                    <Input placeholder='请输入仲裁员' />
                  </Item>
                </Col>
              </Row>
              <Row>
                <Col span={16} />
                <Col span={8}>
                  <Item>
                    <div className={style['search-btns']}>
                      <Button type='primary' ghost htmlType='submit'>搜索</Button>
                      <Button htmlType='reset' onClick={() => this.resetHandle()}>重置
                      </Button>
                      {/* {this.renderToggleBtns()} */}
                    </div>
                  </Item>
                </Col>
              </Row>
            </Form>
          </div>
        </div>
        <div className={style['table-container']}>
          <Table loading={this.state.loading} columns={columns} dataSource={this.state.list} pagination={this.state.pagination} onChange={(...args) => this.tableChange(...args)} />
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addWindow: (i) => dispatch(addWindow(i))
  }
})

export default connect(mapState, mapDispatch)(AllWarningCase)
